package org.iblink.core.domain.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.iblink.core.domain.dao.AssetDao;
import org.iblink.core.domain.model.Asset;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * Implementation class for accessing asset from database.
 * 
 * @author tpares
 *
 */
public class AssetDaoImpl extends HibernateDaoSupport implements AssetDao {
  
  private static final Logger logger = Logger.getLogger(AssetDaoImpl.class.getName());

  @Override
  public void deleteAsset(long assetId) {
    logger.debug("Delete asset " + assetId);
    final Asset asset = getHibernateTemplate().load(Asset.class, assetId);
    getHibernateTemplate().delete(asset);
  }

  @Override
  public Asset getAsset(long assetId) {
    return getHibernateTemplate().load(Asset.class, assetId);
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<Asset> getAssetsForCategory(long categoryId) {
    final StringBuffer query = new StringBuffer();
    query.append("select a from Asset");
    query.append(" as a inner join a.categories as c");
    query.append(" where c.id = :categoryId order by a.name");
    
    return getHibernateTemplate().findByNamedParam(query.toString(), "categoryId", categoryId);
  }

  @Override
  public void saveAsset(Asset asset) {
    getHibernateTemplate().saveOrUpdate(asset);
  }
  
  @SuppressWarnings("unchecked")
  @Override
  public Asset findByPath(String path) {
    List assets = getHibernateTemplate().findByNamedParam("select a from Asset as a where a.path = :path", "path", path);
    
    return (assets == null || assets.isEmpty()) ? null : (Asset)assets.get(0);
  }
}
